/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "math.h"
#include "mpu6050.h"
#include "bsp_dwt.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
short accData[3];
float ax,ay,az;

short gyroData[3];
float wx,wy,wz;

float q0=1.0,q1=0.0,q2=0.0,q3=0.0;
float a,b,c,d;
float roll,pitch,yaw;

float kp=1,ki=0.06;
float ex,ey,ez;
float exInt,eyInt,ezInt;
float vx,vy,vz;

float norm;
float yaw_accel ;
float yaw_drift = 0;

float yaw_prev = 0;
float alpha=0.05;
float x;

uint32_t DWT_CNT;
float dt;
float t;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define PI 3.1415926
#define halfT 0.005 
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

void normalize_accel(){
	float a = sqrt(ax*ax+ay*ay+az*az);
	ax /= a;
	ay /= a;
	az /= a;
	
}
void normalize_v(){
	float v = sqrt(ax*ax+ay*ay+az*az);
	vx /= v;
	vy /= v;
	vz /= v;
}
void normalize_quaternion() {
    float mag = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
    q0 /= mag;
    q1 /= mag;
    q2 /= mag;
    q3 /= mag;
}

float rad2deg(float rad) {
    return rad * 180.0 / PI;
}

void quaternion2euler() {
    roll = rad2deg(atan2(2*q0*q1 + 2*q2*q3, 1 - 2*q1*q1 - 2*q2*q2));
    pitch = rad2deg(asin(2*q0*q2 - 2*q1*q3));
//	if( (1 - 2*q2*q2 - 2*q3*q3<0.001)&&(1 - 2*q2*q2 - 2*q3*q3>-0.001))
//	{
//		x=0.001;
//	}
//	else
//	{
//		x = 1 - 2*q2*q2 - 2*q3*q3<0.001;
//	}
    yaw = rad2deg(atan2(2*q0*q3 + 2*q1*q2,1 - 2*q2*q2 - 2*q3*q3));
	
	
//		float ay_norm = sqrt(ax * ax + ay * ay + az * az);
//		
//		if (ay_norm > 0.1) {
//		yaw_accel	= rad2deg(atan2(-ax, ay));
//			
//		yaw = alpha * ( yaw+wz*dt) + (1-alpha) * yaw_accel;
//}
//	yaw = yaw - yaw_drift;
}
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	MPU6050_Init();
	DWT_Init(72);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		HAL_Delay(1);
		dt = DWT_GetDeltaT(&DWT_CNT);
	//	MPU6050ReadID();
		
		MPU6050ReadAcc(accData);
		MPU6050ReadGyro(gyroData);
		
		ax = ((float)accData[0]);
		ay = ((float)accData[1]);
		az = ((float)accData[2]);
		
		wx = (((float)gyroData[0])+452.1)* (PI / 180.0) / 131.0;
		wy = (((float)gyroData[1])+14.55)* (PI / 180.0) / 131.0;
		wz = (((float)gyroData[2])+87.5)* (PI / 180.0) / 131.0;
		
		vx = 2*(q1*q3-q0*q2);
		vy = 2*(q0*q1+q2*q3);
		vz = q0*q0-q1*q1-q2*q2+q3*q3;
		
		normalize_accel();
		normalize_v();
		//normalize_gyro();?
		ex = (ay*vz - az*vy);                               
    ey = (az*vx - ax*vz);
    ez = (ax*vy - ay*vx);
		
		exInt = exInt + ex*ki;
    eyInt = eyInt + ey*ki;
    ezInt = ezInt + ez*ki*0;
		
		wx = wx + kp*ex + exInt;
    wy = wy + kp*ey + eyInt;
    wz = wz + kp*ez + ezInt;
		
		a=q0;
		b=q1;
		c=q2;
		d=q3;
		
		q0 = a + (-b*wx - c*wy - d*wz)*halfT;
    q1 = b + (a*wx + c*wz - d*wy)*halfT;
    q2 = c + (a*wy - b*wz + d*wx)*halfT;
    q3 = d + (a*wz + b*wy - c*wx)*halfT;  
		
		normalize_quaternion();
		
		quaternion2euler();
		
//		printf("%f\n", wz*1000);
//		printf("pitch=%f\n",pitch);
//  	printf("yaw=%f\n",yaw);
	printf("roll=%f,pitch=%f,yaw=%f\n", roll,pitch,yaw);
//				printf("roll=%f,pitch=%f\n", roll,pitch);
//		printf("wx=%f,wy=%f,wz=%f\n", wx, wy, wz);
//		printf("%f %f %f\n", wx, wy, wz);
//		printf("ax=%f,ay=%f,az=%f\n", (2*q0*q1 + 2*q2*q3)/( 1 - 2*q1*q1 - 2*q2*q2), 2*q0*q2 - 2*q1*q3, (2*q0*q3 + 2*q1*q2)/(1 - 2*q2*q2 - 2*q3*q3));
//		printf("q0=%f,q1=%f,q2=%f,q3=%f\n", q0, q1, q2, q3);
//	printf("gyroData[0] = %d gyroData[1] = %d gyroData[2] = %d\n", gyroData[0],gyroData[1],gyroData[2]);
//	printf("accData[0] = %d accData[1] = %d accData[2] = %d\n", accData[0],accData[1],accData[2]);
//	printf("\n");
//	printf("**********************************************************************\n");
//	printf("\n");
//printf("%d\n", gyroData[2]);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
